<?php
namespace app\command;

use app\facade\Redis;
use app\helps\MoneyBonusHelper;
use app\helps\MoneyContractHelper;
use app\helps\MoneyMtHelper;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;

/**
 * Class Profit
 * @package app\command
 */
class OrderSend extends Command
{
    protected $contractHelper = null;
    protected  $mtHelper =null;
    protected function configure()
    {
        $this->setName('OrderSend')
            ->setDescription('发货');
    }


    protected function execute(Input $input, Output $output){

        while (true){
            $rows = Db::table("tb_order")->where("status",0)->where("deal",0)->order("id asc")->select();
            echo json_encode($rows)."\n";
            foreach ($rows as $index=>$row){
                $type= "order";
                //  {   "phoneNum": "18775360903", 	 "goodsId": "45964", 	"planId": "7541", 	"tariffId": "3812", 	  "operType": 0, 		"smsCode": "819993", 		  "businessId": "20200704160223123456", }
                $params=[];
                $params["phoneNum"]=$row["mobile"];
                $params["goodsId"]=$row["goods_id"];
                $params["planId"]=$row["plan_id"];
                $params["tariffId"]=$row["tariff_id"];
                $params["operType"]=0;
                $params["smsCode"]=$row["sms_code"];
                $code = rand(100000, 999999);
                $params["businessId"]=date("YmdHis").$code;
                $body= json_encode($params,true);
                $res = $this->flowPost($type,$body);

                if ($res&&$res["status"]==1){
                    $sqldata=[];
                    $sqldata["remark"]= "发货成功";
                    if ($res["data"]){
                        if ($res["data"]["orderId"]){
                            $sqldata["yd_oid"]= $res["data"]["orderId"];

                        }
                        // if (isset($res["data"]["crmOrderId"])){
                        //     $sqldata["yd_crm"]= $res["data"]["crmOrderId"];

                        // }
                    }
                    $sqldata["status"]= 1;
                    $sqldata["deal"]= 0;
                    $sqldata["send_time"]=time();
                    Db::table("tb_order")->where("id",$row["id"])->update($sqldata);

                    echo Db::table("tb_order")->getLastSql();
                }else{
                    $sqldata=[];
                    $sqldata["remark"]= "发货失败";
                    if ($res["msg"]){
                        $sqldata["remark"] ="发货失败:".$res["msg"];
                    }
                    $sqldata["status"]= 2;
                    $sqldata["deal"]= 0;
                    $sqldata["send_time"]=time();
                    Db::table("tb_order")->where("id",$row["id"])->update($sqldata);
                    echo "订单：".$row["id"].$sqldata["remark"];
                }
            }

            sleep(5);
        }
    }


    public function flowPost($method,$body){
        echo $body."\n";
        $test = "http://gx.clientaccess.10086.cn/shop/exterInf/flow/".$method;
        $dev = "https://www.gx.10086.cn/elecdms/exterInf/flow/".$method;
        $url = $dev;

        $secret = "e8b013eae317479fb09c088b1b8068f0";
        $appkey = "itybk1581390088145";
//        $secret = "9fce86b46bc2996b36a56477793238ff";
//        $appkey = "zengdudu";
        $channelId = "EB001";

        $head=[];
        $head["appkey"]=$appkey;
        $head["channelId"]=$channelId;
        $param=[];
        $param["Head"]=$head;
        $param["Body"]=$body;
        $pString = base64_encode(json_encode($param,true));
        $res =$this->getFlowUrl($secret,$pString,$url,$appkey);

        return $res;
    }

    public function getFlowUrl($secret,$pString,$url,$appkey){
        $api ="http://127.0.0.1:8080/encode?secret=".$secret."&str=".$pString;
        echo $api."\n";
        $res = $this->request_post($api);

        if ($res&&$res["code"]==200){
            $resData = $res["data"];
            $url = $url."?requestParam=".$resData["requestParam"]."&sign=".$resData["sign"]."&appkey=".$appkey;
            $res = $this->request_post($url);
            echo json_encode($res)."\n";
            if ($res&&$res["resultCode"]=='0000'){
                return [
                    'status' => 1,
                    'msg'    => $res["resultMsg"],
                    'data' => $res["result"],
                ];
            }else{
                return [
                    'status' => 0,
                    'msg'    => $res["resultMsg"],
                    'url' => $url,
                ];
            }
        }else{
            return [
                'status' => 0,
                'msg'    => "秘钥解析失败",
            ];
        }

        // $result = '{"resultCode":"0000","resultMsg":"\u529e\u7406\u6210\u529f\uff01","result":{"orderId":"22020072502291996988669107677483"}}';
        // $res= json_decode($result,true);
        //  return [
        //             'status' => 1,
        //             'msg'    => $res["resultMsg"],
        //             'data' => $res["result"],
        //         ];

    }

    function request_post($url = '',$header=false) {

        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据不直接输出
        curl_setopt($ch, CURLOPT_ENCODING, "gzip"); //指定gzip压缩
        //add header
        if(!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //add ssl support
        if(substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //SSL 报错时使用
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    //SSL 报错时使用
        }

        try {
            $content = curl_exec($ch); //执行并存储结果
        } catch (\Exception $e) {
            $this->_log($e->getMessage());
        }
        $curlError = curl_error($ch);
        if(!empty($curlError)) {
            $this->_log($curlError);
        }
        curl_close($ch);

//        print_r($url);
//        //显示获得的数据
//        print_r($content);


        return json_decode($content,true);
    }

}
